<template>
  <div ref="wrapRef" :style="{ height, width }"></div>
  <Drawer @register="register" />
</template>

<script lang="ts">
  import { watch } from 'vue';
  import { defineComponent, ref, nextTick, onMounted } from 'vue';
  import { useScript } from '/@/hooks/web/useScript';
  import { useDrawer } from '/@/components/Drawer';
  import Drawer from './Drawer.vue';
  import greenMarker from '@/assets/mapimg/greer.png';
  import redMarker from '@/assets/mapimg/red.png';
  import yellowMarker from '@/assets/mapimg/yellow.png';
  import lanseMarker from '@/assets/mapimg/lanse.png';
  const A_MAP_URL = 'https://webapi.amap.com/maps?v=2.0&key=881c3a75178396f161d6ed9cf47bea03';
  export default defineComponent({
    components: { Drawer },
    name: 'AMap',
    props: {
      width: {
        type: String,
        default: '100%',
      },
      height: {
        type: String,
        default: 'calc(100vh - 278px)',
      },
      mapData: {
        type: Array,
        default: () => [],
      },
    },

    setup(props) {
      nextTick(() => {});
      const [register, { openDrawer, setDrawerProps }] = useDrawer();
      const wrapRef = ref<HTMLDivElement | null>(null);
      const { toPromise } = useScript({ src: A_MAP_URL });
      async function initMap() {
        await toPromise();
        await nextTick();
        const wrapEl = wrapRef.value;
        if (!wrapEl) return;
        const AMap = (window as any).AMap;
        const map = new AMap.Map(wrapEl, {
          zoom: 11,
          center: [108.949074, 34.264006], // 西安的中心点
          viewMode: '3D',
        });
        // 添加多个标记到地图上
        console.log(props.mapData, '123');

        props.mapData.forEach((markerData) => {
          const lng = parseFloat(markerData.longitude);
          const lat = parseFloat(markerData.latitude);

          let iconUrl = '';
          switch (markerData.statusCode) {
            case '1':
              iconUrl = greenMarker;
              break;
            case '2':
              iconUrl = yellowMarker;
              break;
            case '3':
              iconUrl = redMarker;
              break;
            case '4':
              iconUrl = lanseMarker;
              break;
            default:
              iconUrl = greenMarker; // 默认绿色图标
          }

          const markerIcon = new AMap.Icon({
            size: new AMap.Size(40, 40),
            image: iconUrl,
            imageSize: new AMap.Size(20, 25),
          });

          const marker = new AMap.Marker({
            position: [lng, lat],
            icon: markerIcon,
            draggable: false,
            cursor: 'pointer',
            raiseOnDrag: true,
          });
          console.log(marker);

          marker.setMap(map);
          var info = [];
          info.push(`<div style="padding:7px 0px 0px 0px ;"><h4>油站名称：${markerData.company}</h4>`);
          // info.push(`<div><h4>施封数量：${markerData.statusCode}</h4>`);
          // info.push(`<p>电话 : ${markerData.phone}   邮编 : 721000</p>`);
          info.push(`<p>地址 : ${markerData.address}</p></div></div>`);

          // 创建 InfoWindow 实例
          const infoWindow = new AMap.InfoWindow({
            content: info.join(''), // 使用 join('') 将数组元素连接成一个字符串
            offset: new AMap.Pixel(15, 10), // 偏移量，使得提示框出现在标记的上方
          });

          // 当标记被鼠标悬停时显示 InfoWindow
          marker.on('mouseover', () => {
            infoWindow.open(map, marker.getPosition());
          });

          // 当鼠标离开标记时关闭 InfoWindow
          marker.on('mouseout', () => {
            infoWindow.close();
          });

          // 当点击标记时，显示抽屉
          marker.on('click', () => {
            openDrawer(true, {
              company: markerData.company,
              regionCode: markerData.regionCode,
            });
          });
        });
      }

      onMounted(() => {
        initMap();
      });
      watch(
        () => props.mapData,
        (newData) => {
          console.log(newData, 'mapData changed'); // 调试信息
          // 重新初始化地图
          initMap();
        },
        { deep: true }
      );
      return { wrapRef, register, openDrawer, setDrawerProps };
    },
  });
</script>
